package com.shopping.mall.core.module.order.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.shopping.mall.core.module.cart.entity.Cart;
import com.shopping.mall.core.module.goodsSpecification.entity.GoodsSpecification;
import com.shopping.mall.core.module.goodsSpecification.mapper.GoodsSpecificationMapper;
import com.shopping.mall.core.module.order.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StockServiceImpl implements StockService {
    @Autowired
    private GoodsSpecificationMapper specificationMapper;
    /**
     * 下单减少库存
     * @param cartList
     */
    @Async
    @Override
    public void reduceStock(List<Cart> cartList) {
        for(Cart cart:cartList){
            GoodsSpecification goodsSpecification=specificationMapper.selectById(cart.getSpecificationId());
            if(goodsSpecification!=null){
                goodsSpecification.setStock(goodsSpecification.getStock()-cart.getNumber());
                if(goodsSpecification.getStock()<0){
                    goodsSpecification.setStock(0);
                }
                specificationMapper.updateById(goodsSpecification);
            }
        }
    }

    /**
     * 取消订单增加库存
     * @param goods
     */
    @Override
    public void addStock(String goods) {
        JSONArray jsonArray=JSONArray.parseArray(goods);
        List<Cart> cartList=jsonArray.toJavaList(Cart.class);
        for(Cart cart:cartList){
            GoodsSpecification goodsSpecification=specificationMapper.selectById(cart.getSpecificationId());
            if(goodsSpecification!=null){
                if (goodsSpecification.getStock()!=null){
                    goodsSpecification.setStock(goodsSpecification.getStock()+cart.getNumber());
                    specificationMapper.updateById(goodsSpecification);
                }
            }
        }
    }
}
